<?php
/**
 * Created by PhpStorm.
 * User: River
 * Email: river0428@gmail.com
 * Date: 2018/12/25
 * Time: 上午10:11
 */

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class RechargeTask extends Model
{
    protected $table = 'recharge_task';

    public $guarded = [];

    public $appends = ['amount', 'recharge_amount', 'type_name', 'status_name','recharge_mode_name'];

    public function detail()
    {
        return $this->belongsTo(RechargeOrderDetail::class, 'recharge_order_detail_id', 'id');
    }

    public function order()
    {
        return $this->belongsTo(RechargeOrder::class, 'recharge_order_id', 'id');
    }

    public static function createTaskByOrder(RechargeOrder $order)
    {
        $shopOrder = ShopOrder::where("order_sn",$order->order_sn)->first();
        if ($shopOrder){
            $recharge_mode = 2;
        }else{
            $recharge_mode = $order->recharge_mode;
        }
        if ($order->type == RechargeOrder::TYPE_RECHARGE) {
            foreach ($order->detail as $item) {
                RechargeTask::createTask($order->oilCard, $item->amount, $item->pay_at, $order->id,$order->user_id,$recharge_mode, $item->id);
            }
        } else {
            RechargeTask::createTask($order->oilCard, $order->recharge_amount, $order->paid_at, $order->id,$order->user_id,$recharge_mode);
        }
    }

    public static function createTask(OilCard $card, $amount, $payAt, $orderId, $userId, $recharge_mode ,$detailId = 0)
    {
        if ($amount < 100) {
            return;
        }
        // 创建充值任务
        $task = [
            'recharge_order_id'        => $orderId,
            'recharge_order_detail_id' => $detailId,
            'user_id'                  => $userId,
            'amount'                   => $amount,
            'sn'                       => str_random(32),
            'card_type'                => $card->type,
            'card_mobile'              => $card->mobile,
            'card_name'                => $card->name,
            'card_no'                  => $card->card_no,
            'pay_at'                   => $payAt,
            'recharge_mode'            => $recharge_mode
        ];

        if ($card->type == OilCard::TYPE_ZSY) {
            $task['pro_id'] = '10008';
            //$task['card_num'] = $amount;
            //RechargeTask::create($task);

            if ($amount >= 1000) {
                $task['card_num'] = 1000;
                RechargeTask::create($task);
                $moreAmount = $amount - 1000;
                if ($moreAmount > 0) {
                    RechargeTask::createTask($card, $moreAmount, $payAt, $orderId,$userId,$recharge_mode, $detailId);
                }
                return;
            }
            if ($amount >= 500) {
                $task['card_num'] = 500;
                RechargeTask::create($task);
                $moreAmount = $amount - 500;
                if ($moreAmount > 0) {
                    RechargeTask::createTask($card, $moreAmount, $payAt, $orderId, $userId,$recharge_mode, $detailId);
                }
                return;
            }
            if ($amount >= 200) {
                $task['card_num'] = 200;
                RechargeTask::create($task);
                $moreAmount = $amount - 200;
                if ($moreAmount > 0) {
                    RechargeTask::createTask($card, $moreAmount, $payAt, $orderId, $userId, $recharge_mode, $detailId);
                }
                return;
            }
            if ($amount >= 100) {
                $task['card_num'] = 100;
                RechargeTask::create($task);
                $moreAmount = $amount - 100;
                if ($moreAmount > 0) {
                    RechargeTask::createTask($card, $moreAmount, $payAt, $orderId,$userId, $recharge_mode,$detailId);
                }
                return;
            }

        } else {
            $task['card_num'] = 1;
            if ($amount >= 1000) {
                $task['pro_id'] = '10004';
                RechargeTask::create($task);
                $moreAmount = $amount - 1000;
                if ($moreAmount > 0) {
                    RechargeTask::createTask($card, $moreAmount, $payAt, $orderId, $userId, $recharge_mode,$detailId);
                }
                return;
            }
            if ($amount >= 500) {
                $task['pro_id'] = '10003';
                RechargeTask::create($task);
                $moreAmount = $amount - 500;
                if ($moreAmount > 0) {
                    RechargeTask::createTask($card, $moreAmount, $payAt, $orderId,$userId, $recharge_mode, $detailId);
                }
                return;
            }
            if ($amount >= 200) {
                $task['pro_id'] = '10002';
                RechargeTask::create($task);
                $moreAmount = $amount - 200;
                if ($moreAmount > 0) {
                    RechargeTask::createTask($card, $moreAmount, $payAt, $orderId, $userId, $recharge_mode, $detailId);
                }
                return;
            }
            if ($amount >= 100) {
                $task['pro_id'] = '10001';
                RechargeTask::create($task);
                $moreAmount = $amount - 100;
                if ($moreAmount > 0) {
                    RechargeTask::createTask($card, $moreAmount, $payAt, $orderId,  $userId, $recharge_mode,$detailId);
                }
                return;
            }
        }
    }

    public function getAmountAttribute()
    {
        switch ($this->pro_id) {
            case '10001':
                return 100;
            case '10002':
                return 200;
            case '10003':
                return 500;
            case '10004':
                return 1000;
            case '10008':
                return $this->card_num;
            default:
                return '未知';
        }
    }

    public function getTypeNameAttribute()
    {
        //if ($this->type == OilCard::TYPE_ZSY) {
        if(strpos($this->attributes['card_no'],'9')===0){
            return '中石油';
        } else {
            return '中石化';
        }
    }

    // 0待充值，1请求充值成功，2请求充值失败，4充值失败，9充值成功
    public function getStatusNameAttribute()
    {
        if ($this->attributes['status'] == 0) {
            return '待充值';
        }
        if ($this->attributes['status'] == 1) {
            return '请求成功';
        }
        if ($this->attributes['status'] == 2) {
            return '请求失败';
        }
        if ($this->attributes['status'] == 4) {
            return '充值失败';
        }
        if($this->attributes['status'] == 7){
            return '已退款';
        }
        if ($this->attributes['status'] == 9) {
            return '充值成功';
        }
    }

    public function getRechargeModeNameAttribute()
    {
        //if ($this->type == OilCard::TYPE_ZSY) {
        if($this->attributes['recharge_mode']==1){
            return '自动';
        } else {
            return '手动';
        }
    }

    public function getRechargeAmountAttribute()
    {
        return $this->attributes['amount'];
    }


    public static function rechargeOrderTaskSynchronization(){
        $tasks = RechargeOrder::query()->orderBy('id','asc')->get();
        foreach ($tasks as $item){
            //根据订单任务同步订单状态
            $taskOrder = RechargeTask::query()->where("recharge_order_id",$item->id)->orderBy("id",'desc')->first();
            if ($taskOrder){
                if ($taskOrder->status==9) {
                    //更新订单状态
                    $item->status = 3;
                    $item->save();
                }elseif($taskOrder->status==7){
                    $item->status = 7;
                    $item->save();
                }else{
                    $item->status = 2;
                    $item->save();
                }
            }
        }
        //根据套餐充值订单同步订单详情
        $orders = RechargeOrder::where("type",1)->orderBy("id","asc")->get();
        foreach ($orders as $item){
            $task = RechargeTask::where("recharge_order_id",$item['id'])->orderBy("id","asc")->get();
            foreach ($task as $value){
                if ($value['status']==9){
                    //同步订单状态
                    RechargeOrderDetail::where("id",$value['recharge_order_detail_id'])->update(["result_status"=>1,"is_paid"=>1,"paid_at"=>$value['pay_at']]);
                }else{
                    RechargeOrderDetail::where("id",$value['recharge_order_detail_id'])->update(["result_status"=>0,"is_paid"=>0,"paid_at"=>(NULL)]);
                }

            }
        }
    }
}